function [rs]=rotate_descriptor(des,theta,norder,lorder)
% function [rs]=rotate_descriptor(des,theta)
%	rotate a flow field descriptor by an angle theta
%	This can be used, for example, to align the flow field according to its principle orientations
%
%	INPUTS:
%		des - M*N matrix of N discriptors, each descriptor has dimension M
%		theta - the rotation angle, can be a scalar or 1*N matrix
%		indicating N different rotaton angles.
%	OUTPUTS:
%		rs	- the resulting rotated descriptor

if(nargin<3)% old taylor's expansion code, let's leave it alone for the moment
    n=numel(des)/2;
    rs=zeros(n,numel(theta));
    for kk=0:n-1
        cc=cos((kk-1)*theta);
        ss=sin((kk-1)*theta);
        ak1=des(2*kk+1);
        ak2=des(2*kk+2);
        rs(2*kk+1,:)=cc.*ak1-ss.*ak2;
        rs(2*kk+2,:)=ss.*ak1+cc.*ak2;
    end
else
    kk=[-lorder-1:norder-1]';
    kk=repmat(kk,[1,size(des,2)]);
    if(size(des,1)~=(lorder+norder+1)*2)
        error('length of the descriptor (size(des,1)) does not match with the order');
    end
    rs=zeros(size(des));
    if(isscalar(theta))
        cc=cos(kk*theta);
        ss=sin(kk*theta);
    else
        cc=cos(kk.*repmat(theta,[size(kk,1) 1]));
        ss=sin(kk.*repmat(theta,[size(kk,1) 1]));
    end
    
    rs(1:2:end,:)=cc.*des(1:2:end,:)-ss.*des(2:2:end,:);
    rs(2:2:end,:)=ss.*des(1:2:end,:)+cc.*des(2:2:end,:);
end